package com.bite.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.constants.Constants;
import com.bite.common.core.domain.TableDataInfo;
import com.bite.common.core.enums.ExamListType;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.common.security.exception.ServiceException;
import com.bite.common.security.service.TokenService;
import com.bite.friend.domain.exam.Exam;
import com.bite.friend.domain.exam.dto.ExamQueryDTO;
import com.bite.friend.domain.exam.vo.ExamVO;
import com.bite.friend.domain.user.UserExam;
import com.bite.friend.domain.user.vo.UserVO;
import com.bite.friend.manager.ExamCacheManager;
import com.bite.friend.manager.UserCacheManager;
import com.bite.friend.mapper.exam.ExamMapper;
import com.bite.friend.mapper.user.UserExamMapper;
import com.bite.friend.service.user.IUserExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class UserExamServiceImpl implements IUserExamService {
    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;


   // private UserCacheManager userCacheManager;

    @Override
    public int enter(String token, Long examId) {
       /* Long userId=ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        UserVO userVO=userCacheManager.getUserById(userId);
        //获取当前用户信息,查看是否被拉黑
        if(userVO.getStatus()==0){
            throw new ServiceException(ResultCode.FAILED_USER_BANNED);
        }*/


        //先查看竞赛是否存在
        Exam exam =examMapper.selectById(examId);
        if (exam == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        //已经开赛的竞赛不能报名
        if (exam.getStartTime().isBefore(LocalDateTime.now()))
        {
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
   //     Long userId=tokenService.getUserId(token,secret);
        Long userId= ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserExam userExam=userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId,examId)
                .eq(UserExam::getUserId,userId)
        );
        //不能重复参赛
        if (userExam != null) {
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        //存redis
        examCacheManager.addUserExamCache(examId,userId);
        userExam=new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        //返回插入数据库结果
        return userExamMapper.insert(userExam);
    }

    //先查询缓存，查询不到再去数据库
    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        Long userId=ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        //从redis中获取竞赛列表数据
        Long total=examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(),userId);
        List<ExamVO> examVOList;

        //说明redis中没存在，从mysql中取
        if (total==null||total==0){
            PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
            examVOList=userExamMapper.selectUserExamList(userId);
            //存到redis
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(),userId);
            total=new PageInfo<>(examVOList).getTotal();
        }else {

            examVOList=examCacheManager.getExamVOList(examQueryDTO,userId);
            total=examCacheManager.getListSize(examQueryDTO.getType(),userId);
        }
        if (CollectionUtil.isEmpty(examVOList)){
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList, total);
    }
}
